package com.haipumi.servlets.backadmin;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.OperatingSystem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import com.haipumi.beans.HardDisk;
import com.haipumi.beans.ServiceInfo;
import com.haipumi.servlets.CommonServlet;

public class BackServerInfo extends CommonServlet {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1049810281451068262L;

	
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		 try {
			 	ServiceInfo si=new ServiceInfo();
			 	
			 	
	            // System信息，从jvm获取
	            property(request,response,si);
	            // cpu信息
	            cpu(request,response,si);
	            // 内存信息
	            memory(request,response,si);
	            // 操作系统信息
	            os(request,response,si);
	            // 文件系统信息
	            file(request,response,si);
	            
	            //super.outData(response, si);
	            //re.setAttribute("ServiceInfo", si);
	            HttpSession session=request.getSession();
	            session.setAttribute("ServiceInfo", si);
	            super.outData(response, si);
	        } catch (Exception e1) {
	            e1.printStackTrace();
	        }
	}
	
	private static void property(HttpServletRequest request, HttpServletResponse response,ServiceInfo si) throws UnknownHostException {
		
		
        Runtime r = Runtime.getRuntime();
        Properties props = System.getProperties();
        InetAddress addr;
        addr = InetAddress.getLocalHost();
        String ip = addr.getHostAddress();
        
        //out.println("本地ip地址: " + ip+"<br/>");
        si.setIp(ip);
        //out.println("本地主机名:  " + addr.getHostName()+"<br/>");
        si.setComputername(addr.getHostName());
        //out.println("JVM可以使用的处理器个数:  " + r.availableProcessors()+"<br/>");
        si.setCpunum(Integer.toString(r.availableProcessors()));
        //out.println("Java的运行环境版本：    " + props.getProperty("java.version")+"<br/>");
        si.setJavaversion(props.getProperty("java.version"));
        //out.println("用户的当前工作目录：  " + props.getProperty("user.dir")+"<br/>");
        si.setUserdocument(props.getProperty("user.dir"));
    }
 
    private static void memory(HttpServletRequest request, HttpServletResponse response,ServiceInfo si) throws SigarException {
        Sigar sigar = new Sigar();
		
        Mem mem = sigar.getMem();
        // 内存总量
        //out.println("内存总量:   " + mem.getTotal() / 1024L + "K av"+"<br/>");
        si.setRomtotal(Long.toString(mem.getTotal()));
        // 当前内存使用量
        //out.println("当前内存使用量:    " + mem.getUsed() / 1024L + "K used"+"<br/>");
        si.setRomuse(Long.toString(mem.getUsed()));
       
    }
 
    private static void cpu(HttpServletRequest request, HttpServletResponse response,ServiceInfo si) throws SigarException {
        Sigar sigar = new Sigar();
        CpuInfo infos[] = sigar.getCpuInfoList();
        CpuPerc cpuList[] = null;
        cpuList = sigar.getCpuPercList();
        double temp=0.0;
        for (int i = 0; i < 2; i++) {// 不管是单块CPU还是多CPU都适用
            CpuInfo info = infos[i];
            //out.println("CPU生产商: " + info.getVendor()+"<br/>");// 获得CPU的卖主，如：Intel
            si.setCpumaker(info.getVendor());
            temp+=printCpuPerc(cpuList[i],si,temp);
        }
        si.setCpuuse(	Double.toString(temp/infos.length));
    }
 
    private static double printCpuPerc(CpuPerc cpu ,ServiceInfo si,double temp) {
       // out.println("CPU总的使用率:   " + CpuPerc.format(cpu.getCombined())+"<br/>");// 总的使用率
//    	if(si.getCpuuse()!=null||!"".equals(si.getCpuuse())){
//    		si.setCpuuse(	Double.toString(cpu.getCombined()+Double.parseDouble(si.getCpuuse()))	);
//    	}else{
//    		si.setCpuuse(	CpuPerc.format(cpu.getCombined()+0.0+Double.parseDouble(si.getCpuuse()))	);
//    	}
    	temp+=cpu.getCombined();
    	return temp;
    }
 
    private static void os(HttpServletRequest request, HttpServletResponse response,ServiceInfo si) {
    	
        OperatingSystem OS = OperatingSystem.getInstance();
        
        //out.println("操作系统名称: " + OS.getVendorName()+"<br/>");
        si.setSystemname(OS.getVendorName());
        // 操作系统的版本号
        //out.println("操作系统的版本号:   " + OS.getVersion()+"<br/>");
        si.setSystemversion(OS.getVersion());
    }
 
   
 
    private static void file(HttpServletRequest request, HttpServletResponse response,ServiceInfo si) throws Exception {
    	
        Sigar sigar = new Sigar();
        FileSystem fslist[] = sigar.getFileSystemList();
        //TODO 有bug fslist.length 长度为5  单实际所需要的长度为4
        
        List<HardDisk> hdlist=new ArrayList<HardDisk>();
//        for (int i = 0; i < fslist.length; i++) {
        for (int i = 0; i < 1; i++) {
        	HardDisk hd=new HardDisk();
        	//out.println("分区的盘符名称" + i);
        	
            FileSystem fs = fslist[i];
            // 分区的盘符名称
            //out.println("盘符名称:   " + fs.getDevName()+"<br/>");
            hd.setName(fs.getDevName());
            // 分区的盘符名称
            //out.println("盘符路径:   " + fs.getDirName()+"<br/>");
            //out.println("盘符标志:   " + fs.getFlags()+"<br/>");//
            // 文件系统类型，比如 FAT32、NTFS
            //out.println("盘符类型:   " + fs.getSysTypeName()+"<br/>");
           	hd.setSystypename(fs.getSysTypeName());
            // 文件系统类型名，比如本地硬盘、光驱、网络文件系统等
            //out.println("盘符类型名:  " + fs.getTypeName()+"<br/>");
            hd.setType(fs.getTypeName());
            FileSystemUsage usage = null;
            usage = sigar.getFileSystemUsage(fs.getDirName());
            switch (fs.getType()) {
            case 0: // TYPE_UNKNOWN ：未知
                break;
            case 1: // TYPE_NONE
                break;
            case 2: // TYPE_LOCAL_DISK : 本地硬盘
                // 文件系统总大小
            	//out.println(fs.getDevName() + "总大小:  " + usage.getTotal()/(1048576) + "GB"+"<br/>");
                hd.setTotalsize(Long.toString(usage.getTotal()/(1048576)));
                // 文件系统已经使用量
            	//out.println(fs.getDevName() + "已经使用量:    " + usage.getUsed()/(1048576) + "GB"+"<br/>");
                hd.setUsedsize(Long.toString(usage.getUsed()/(1048576)));
                break;
            case 3:// TYPE_NETWORK ：网络
                break;
            case 4:// TYPE_RAM_DISK ：闪存
                break;
            case 5:// TYPE_CDROM ：光驱
                break;
            case 6:// TYPE_SWAP ：页面交换
                break;
            }
            double temp=(usage.getUsed()/(1048576))/(usage.getTotal()/(1048576));
            hd.setZhanyonglv(Integer.toString((int)(temp*100)));
            hdlist.add(hd);
        }
        si.setDisklist(hdlist);
        return;
    }
 
   
 
    

}
